<?php

namespace app\common\service\pay;


use app\common\service\ApiService;

class AlipayService1 extends ApiService
{

    private $apiInstance;

    public function __construct()
    {
        require_once app()->getRootPath() . '/vendor/alipaysdk/openapi/v2/aop/AopClient.php';
        require_once app()->getRootPath() . '/vendor/alipaysdk/openapi/v2/aop/AopCertClient.php';
        require_once app()->getRootPath() . '/vendor/alipaysdk/openapi/v2/aop/AopCertification.php';
        require_once app()->getRootPath() . '/vendor/alipaysdk/openapi/v2/aop/AlipayConfig.php';

        $appId = env('ALIPAY.ALIPAY_APPID') ?? '';
        if (empty($appId)) {
            getResponseException('请配置支付宝APPID', [], 1, 'ERROR');
        }
        $privateKey = env('ALIPAY.ALIPAY_PRIVATE_KEY') ?? '';
        if (empty($privateKey)) {
            getResponseException('请配置支付宝PRIVATE_KEY', [], 1, 'ERROR');
        }
        $publicKey = env('ALIPAY.ALIPAY_PUBLIC_KEY') ?? '';
        if (empty($publicKey)) {
            getResponseException('请配置支付宝PUBLIC_KEY', [], 1, 'ERROR');
        }
        $alipayConfig = new \AlipayConfig();
        $alipayConfig->setAppId($appId);
        $alipayConfig->setCharset("utf-8");
        $alipayConfig->setFormat("json");
        $alipayConfig->setSignType("RSA2");
        $alipayConfig->setServerUrl('https://openapi.alipay.com');
        $alipayConfig->setPrivateKey($privateKey);
        $alipayConfig->setAlipayPublicKey($publicKey);
        $alipayConfig->setEncryptKey('shuoBaAi');
        $this->apiInstance = new \AopClient($alipayConfig);
    }

    /**
     * 支付宝扫码支付
     */

    public function scanCodePay($orderNo, $totalAmount, $subject, $notifyUrl, $timeoutExpress)
    {
        require_once app()->getRootPath() . '/vendor/alipaysdk/openapi/v2/aop/request/AlipayTradePrecreateRequest.php';
        $request = new \AlipayTradePrecreateRequest();
        $model = [
            'out_trade_no' => $orderNo,
            'total_amount' => $totalAmount,
            'subject' => $subject,
            'product_code' => 'QR_CODE_OFFLINE',
            'timeout_express' => $timeoutExpress
        ];
        $request->setBizContent(json_encode($model, JSON_UNESCAPED_UNICODE));
        $responseResult = $this->apiInstance->execute($request);
        $responseApiName = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $response = $responseResult->$responseApiName;
        if (!empty($response->code) && $response->code == 10000) {
            echo("调用成功");
        } else {
            echo("调用失败");
        }
    }

}
